﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

    public class TimerMgr:SingLon<TimerMgr>
    {
        public bool ISRuning = false;
        public event Action<float> _timerLoopCallback;
        public Timers CreateTimer(float deltaTime, int repeatTimes, Action<float> callback)
        {
            var timer=new Timers();
            timer.DeltaTime = deltaTime;
            timer.RepeatTimes = repeatTimes;
            //timer.Callback = callback;
             _timerLoopCallback += callback;
             return timer;
        }

        public void Loop(float delataTime)
        {
            if (!ISRuning)
            {
                return;
            }

            if (_timerLoopCallback !=null)
            {
                _timerLoopCallback(delataTime);
            }
        }

        public void Start()
        {
            ISRuning = true;
        }

        public void Stop()
        {
            ISRuning = false;
        }
    }

public class Timers
{
    /// <summary>
    /// 间隔时间
    /// </summary>
    public float DeltaTime;
    /// <summary>
    /// 次数
    /// </summary>
    public int RepeatTimes=-1;//默认无限执行
    public Action Callback;
    /// <summary>
    /// 计时的持续时间
    /// </summary>
    public float _duringTime;
    /// <summary>
    /// 已经执行次数
    /// </summary>
    public int RepeatNum;
    public void Start( )
    {
        TimerMgr.Instance._timerLoopCallback += Loop;
    }
    public void Loop(float deltaTime)
    {
        _duringTime += deltaTime;
        //判断间隔时间
        if (_duringTime>=DeltaTime)
        {
            _duringTime = _duringTime - DeltaTime;
            if (Callback !=null)
            {
                Callback();
            }

            RepeatNum++;
            if (RepeatNum>=RepeatTimes&& RepeatTimes >0)
            {
                Stop();
            }
        }

    }

    private void Stop()
    {
        TimerMgr.Instance._timerLoopCallback -= Loop;
    }

    private void Reset()
    {
        _duringTime = 0;
        RepeatNum = 0;
    }
}
